package com.thor.palmmall.card.provide;

import java.io.IOException;

import org.apache.commons.io.IOUtils;
import org.apache.log4j.Logger;
import org.springframework.http.HttpRequest;
import org.springframework.http.client.ClientHttpRequestExecution;
import org.springframework.http.client.ClientHttpRequestInterceptor;
import org.springframework.http.client.ClientHttpResponse;

/**
 * @author liyang
 * @since 0.1
 */
public class LoggingRequestInterceptor implements ClientHttpRequestInterceptor {
  final static Logger logger = Logger.getLogger(LoggingRequestInterceptor.class);

  @Override
  public ClientHttpResponse intercept(HttpRequest request, byte[] body,
      ClientHttpRequestExecution execution) throws IOException {
    traceRequest(request, body);
    ClientHttpResponse response = execution.execute(request, body);
    traceResponse(response);
    return response;
  }

  private void traceRequest(HttpRequest request, byte[] body) throws IOException {
    logger.info(request.getURI());
    logger.info( request.getMethod());
    logger.info( request.getHeaders());
    logger.info( new String(body, "UTF-8"));
  }

  private void traceResponse(ClientHttpResponse response) throws IOException {
    logger.info(response.getStatusCode());
    logger.info(response.getStatusText());
    logger.info(response.getHeaders());
    logger.info(IOUtils.toString(response.getBody(), "UTF-8"));
  }

}
